package uri_test;

import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Ajie
 * @date 2021-02-06
 * @function
 */
public class UriDemo {
    private static String uriStr ="https://10.20.20.9/bbox-service/api/devapi/callback/config/cache/ba14ee56847bd5272059851bfecf9c0e/1617948049000000003/FC6N2219230048-1617948049000000003?" +
            "redisKey=config_redis_fd10f9c0697844eeb59a069e32f2174f"
            +"&language=zh";
    public static void main(String[] args) {

/*       android 有直接去parameter的api
        String path = "http://www.test.com/payment_m.aspx?action=confirm&order_no=on123456&order_money=99.99&return_url=test/return_url.aspx";
        Uri uriStr = Uri.parse(path);
        String action = uriStr.getQueryParameter("action"); //解析参数
        String order_no = uriStr.getQueryParameter("order_no");//解析参数
        String order_money = uriStr.getQueryParameter("order_money");//解析参数
        String return_url = uriStr.getQueryParameter("return_url");//解析参数
        String pa = uriStr.getLastPathSegment();//解析最后一个地址段，即payment_m.aspx  */


        URI uri = URI.create(UriDemo.uriStr);
        String query = uri.getQuery();
        System.out.println(uri.getQuery());


        UrlUtil.UrlEntity parse = UrlUtil.parse(uriStr);
        Iterator<Map.Entry<String, String>> iterator = parse.params.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            System.out.println(next.getKey()+"--"+next.getValue());
        }
    }
}
class UrlUtil {

    public static class UrlEntity {
        /**
         * 基础url
         */
        public String baseUrl;
        /**
         * url参数
         */
        public Map<String, String> params;
    }

    /**
     * 解析url
     *
     * @param url
     * @return
     */
    public static UrlEntity parse(String url) {
        UrlEntity entity = new UrlEntity();
        if (url == null) {
            return entity;
        }
        url = url.trim();
        if (url.equals("")) {
            return entity;
        }
        String[] urlParts = url.split("\\?");
        entity.baseUrl = urlParts[0];
        //没有参数
        if (urlParts.length == 1) {
            return entity;
        }
        //有参数
        String[] params = urlParts[1].split("&");
        entity.params = new HashMap<>();
        for (String param : params) {
            String[] keyValue = param.split("=");
            entity.params.put(keyValue[0], keyValue[1]);
        }

        return entity;
    }
}
